using System;
using System.Configuration;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.Bytecode;
using NhJump.Persistence.Wcf.Autofac.Model;
using Configuration = NHibernate.Cfg.Configuration;
using Environment = NHibernate.Cfg.Environment;

namespace NhJump.Persistence.Wcf.Autofac.Repositories
{
    public class NHibernateConfigProvider : INHibernateConfigProvider
    {
        private readonly string _connectionStringName;

        public NHibernateConfigProvider(string connectionStringName)
        {
            _connectionStringName = connectionStringName;
        }

        public Configuration GetConfiguration()
        {
            var connectionString = GetConnectionString();
            var config = Fluently.Configure()
                .Database(MySQLConfiguration.Standard.ConnectionString(connectionString))
                .Mappings(m => m.HbmMappings.AddFromAssemblyOf<Customer>())
                .ExposeConfiguration(c => c.SetProperty(Environment.ReleaseConnections, "on_close"))
                .ExposeConfiguration(
                    c =>
                        c.SetProperty(Environment.ProxyFactoryFactoryClass,
                            typeof (DefaultProxyFactoryFactory).AssemblyQualifiedName))
                //.ExposeConfiguration(c => c.SetProperty(Environment.Hbm2ddlAuto, "create"))
                .ExposeConfiguration(c => c.SetProperty(Environment.ShowSql, "true"))
                //.ExposeConfiguration(BuildSchema)
                .BuildConfiguration();

            if (config == null)
                throw new Exception("Cannot build NHibernate configuration");

            return config;
        }

        private string GetConnectionString()
        {
            var connectionString = ConfigurationManager.ConnectionStrings[_connectionStringName];
            if (connectionString == null)
                throw new Exception(String.Format("Connection string '{0}' not found", _connectionStringName));
            return connectionString.ConnectionString;
        }

        private static void BuildSchema(Configuration config)
        {
            //new SchemaExport(config).SetOutputFile(@"./Schema.sql").Create(true, false);
        }
    }
}